{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# perface"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们每天都要面对数据，数据库CRUD操作的能力对每个任务都至关重要。无论你是开发网页，桌面或其他应用，他们都需要快速且安全的接入数据。关系型数据库仍然是储存数据最主流的手段之一。\n",
    "\n",
    "SQL是操作数据的利器，不过有时候要整合到应用里非常麻烦。作为一个Pythoner，你可能需要通过ODBC接口或者数据库API，用一些字符串生成查询。虽然这些方法可以有效的处理数据，但是数据安全和修改变得很困难。\n",
    "\n",
    "这本书将介绍一个非常强大且具有灵活性的Python库SQLAlchemy，可以跨越关系型数据库与传统编程直接的鸿沟。SQLAlchemy允许你使用原始的SQL语言查询，更鼓励使用更高级的Pythonic展示方式和更友好的方法实现数据的查询和更新。它提供工具让你一次性把应用的类和对象映射成数据库的表，然后就可以不再理会表结构了，还可以让你不断优化模型的性能。\n",
    "\n",
    "SQLAlchemy功能强大且充满柔性，但它还是有点复杂。SQLAlchemy教程只介绍了它的冰山一角，尽管在线文档也很全，但是更适合做参考书，不适合做教程。这本书的目的是要成为一个学习工具和一个方便的参考，帮你快速完成任务。\n",
    "\n",
    "本书内容用的SQLAlchemy是1.0版本；但是之前的版本都可以用。0.8版可能需要一点小改动，大部分都是源自0.5版。\n",
    "\n",
    "这本书分成三部分：SQLAlchemy Core，SQLAlchemy ORM和一个Cookbook部分。前两部分尽可能的做到一致性。我们有意在两个部分用同意的例子，目的是让你更方便的比较两种方式的用法。因此，你也可以根据自己的需要阅读本书SQLAlchemy Core和SQLAlchemy ORM的章节。\n",
    "\n",
    "<!-- TEASER_END-->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#  1.SQLAlchemy简介"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SQLAlchemy是一个与数据库进行交互的库。它可以让你用Python的类和语句创建数据模型来查询数据。在2005年由Mike Bayer创建，SQLAlchemy被许多公司使用，已经渐渐成为Python处理关系型数据库的一种主流手段。\n",
    "\n",
    "它可以连接许多数据库，包括 Postgres，MySQL，SQLite和Oracle等等。也提供了一种通用的接口支持其他关系型数据库。Amazon的Redshift数据库，作为Postgres的一种变体，就是SQLAlchemy社区对数据库支持的好榜样。\n",
    "\n",
    "本章，我们将首先解释为什么要用SQLAlchemy，然后介绍两个主要模型并连接一个数据库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 为什么用SQLAlchemy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用SQLAlchemy的主要原因是，把你从底层的数据库和SQL奇葩语法中解放出来。SQLAlchemy将常用语句和类型和SQL语句对应起来，让你可以更容易地理解数据库类型，而不需要担心太多细节。这样在处理像Oracle到PostgreSQL数据库这类的迁移工作，或从一个应用数据库到数据仓库时，事情就简单了。它还能确保数据在增加到数据库之前是经过安全的，适当转义处理的。这样可以避免SQL注入之类的事情发生。\n",
    "\n",
    "SQLAlchemy通过两个主要的模型来实现灵活的操作：SQL表达式语言（通常也叫Core）和ORM（Object-relational mapping，对象关系映射）。这两个模型可以根据你的需要独立使用，也可以合在一起使用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### SQLAlchemy Core和SQL表达式语言"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SQL表达式语言是用Pythonic方式的来表达SQL语句和表达式，只是对传统的SQL语言的轻微抽象。它侧重于实用数据库的模式（schema，其实是具体到一个Tabel和View等），但是它实现了不同数据库之间标准化的接口。SQL表达式语言也是SQLAlchemy ORM的基础。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ORM"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SQLAlchemy ORM与你在其他语言里遇到的ORM类似。它侧重于应用的Domain Model（一种将数据与其行为集成在一起的模式），借助工作单元的模式来维护对象状态。它还在SQL表达式语言之上增加了一层抽象，让用户可以更容易的操作数据库。你可以把ORM和SQL表达式语言结合起来构建强大的应用。ORM构建了一个声明式的系统，与许多其他ORM模型（如Ruby on Rails）使用的 active-record systems类似。\n",
    "\n",
    "虽然ORM非常有用，但是你要注意，类的很多用法与数据库的工作方式是不一样的。我们将在后面的章节介绍这些差异。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Core和ORM的选择\n",
    "\n",
    "究竟是选择Core还是ORM作为应用的数据链接层呢？除了个人喜好，理由可以归结为一些影响因素。这两种模式的语法不太一样，但Core和ORM最大的差异是Core对数据模式和[业务对象（business objects）](https://en.wikipedia.org/wiki/Business_object)的不同处理方式。\n",
    "\n",
    "SQLAlchemy Core是以模式为中心，和普通SQL一样有表，键和索引等。SQLAlchemy Core最擅长的时数据仓库，报表分析，以及其他使用数据查询和其他操作可以牢牢掌控的地方。它拥有强大的数据库连接池（ connection pool）和数据结果集（ResultSet）优化，非常适合处理大量数据，甚至多数据库也适用。\n",
    "\n",
    "但是，如果你更侧重于[领域驱动设计(domain driven design)](https://en.wikipedia.org/wiki/Domain-driven_design)，那么ORM就可以将原数据和业务对象的底层的模式和结构大部分细节都封装起来。这样封装让数据库连接更简单，更像Python代码。大多数应用都更适合按照这种方法建模。ORM可以用一种非常高效的方法把领域驱动设计方法导入传统应用，或者改造原来带有原始SQL语句的应用。还有一个好处就是，通过对底层数据库的合理抽象，ORM让开发者把精力更多地集中在业务流程的实现上。\n",
    "\n",
    "不过，ORM是建立在SQLAlchemy Core基础之上的，你可以把处理MySQL的同样方式用于Oracle的数据仓库和Amazon Redshift数据库。当你需要业务对象和仓库数据时，ORM可以无缝的衔接每个环节。\n",
    "\n",
    "- 如果你的应用框架已经使用了ORM，但是想要更强大的报表功能，使用Core\n",
    "- 如果你不想像普通SQL一样以模式为中心，用ORM\n",
    "- 如果你的数据不需要业务对象，用Core\n",
    "- 如果你把数据看成业务对象，用ORM\n",
    "- 如果要建立快速原型，用ORM\n",
    "- 如果你既要业务对象，又要其他数据无关的功能（报表，数据分析等等），两个都用。\n",
    "\n",
    "知道了如何选择Core和ORM，我们介绍SQLAlchemy的安装与数据库连接方法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## SQLAlchemy安装与数据库连接\n",
    "\n",
    "SQLAlchemy支持Python 2.6+，Python 3.3+和Pypy 2.1+，强烈推荐conda安装，pip也可以（Python 2.7.5+和Python 3.4+自带pip）。\n",
    "```bash\n",
    "conda install sqlalchemy\n",
    "\n",
    "or \n",
    "\n",
    "pip install sqlalchemy\n",
    "```\n",
    "\n",
    "### 安装数据库驱动\n",
    "\n",
    "SQLAlchemy默认支持SQLite3，不需要安装驱动；但是，其他数据库都需要用符合Python的DBAPI（PEP-249）标准的驱动。这些DBAPI提供了与各种数据库进行交互的方言，可以体现不同数据库独有的特性。不同的数据库也可能有多个不同的DBAPI，下面主要介绍PostgreSQL和MySQL数据库的驱动。\n",
    "\n",
    "#### PostgreSQL\n",
    "[Psycopg2](http://initd.org/psycopg/)提供了PostgreSQL的驱动，可以用`pip install psycopg2`安装。\n",
    "#### MySQL\n",
    "[PyMySQL](https://github.com/PyMySQL/PyMySQL)是MySQL的驱动，可以用`pip install pymysql`安装。SQLAlchemy支持MySQL 4.1+版本，由于之前的版本密码工作方式不同。如果某个类型只存在于MySQL的特定版本中，那么SQLAlchemy不会支持那些没有该类型的MySQL版本使用该类型。用MySQL时，如果SQLAlchemy的某个函数不能正常运行，建议看看MySQL的文档。\n",
    "### Others\n",
    "关于其他数据库的SQLAlchemy支持，请参考SQLAlchemy文档。Drizzle，Firebird，Oracle， Sybase，Microsoft SQL Server都支持。IBM DB2，Informix，Amazon Redshift，EXASolution，SAP SQL Anywhere，Monet等数据库也有SQLAlchemy社区支持。额外的方言也可以由SQLAlchemy支持，在第八章：自定义方言里面有介绍。\n",
    "\n",
    "有了DBAPI连接件，我们再看看如何连接数据库。\n",
    "\n",
    "\n",
    "### 连接数据库\n",
    "\n",
    "连接数据库需要SQLAlchemy引擎，SQLAlchemy引擎为数据库执行SQL语句创建了一个常用的接口。引擎通过封装一个数据库连接池和方言来实现不同数据库类型统一的接口。这样做使得Python代码不需要关心不同数据库DBAPI之间的差异。SQLAlchemy提供了一个带连接字符串（connection string）和一些参数的函数来创建引擎。连接字符串形式如下：\n",
    "\n",
    "- 数据库类型（SQLite，Postgres，MySQL等）\n",
    "- 默认数据库类型的方言（Psycopg2，PyMySQL等）\n",
    "- 验证信息（用户名和密码）\n",
    "- 数据库的位置（文件名或数据库服务器地址）\n",
    "- 数据库服务器端口（可选）\n",
    "- 数据库名称（可选）\n",
    "\n",
    "SQLite数据库连接字符串就是一个文件或储存位置。例1-1中，第二行表示SQLAlchemy连接了当前文件夹中的一个SQLite数据库文件`cookies.db`，第三行是连接内存数据库，第四、五行分别是Unix和Windows系统中的全路径文件。Windows系统路径名称分隔符（`\\`）在Python中是`'\\\\'`或`r'\\'`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import create_engine\n",
    "engine = create_engine('sqlite:///cookies.db')\n",
    "engine2 = create_engine('sqlite:///:memory:')\n",
    "engine3 = create_engine('sqlite:////home/cookiemonster/cookies.db')\n",
    "engine3 = create_engine('sqlite:///c:\\\\Users\\\\cookiemonster\\\\cookies.db')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">`create_engine`函数创建了一个引擎实例，但是，它并没有真正打开链接，直到一个动作要求引擎执行时才会执行，比如查询或新建数据。\n",
    "\n",
    "下面再让我们创建一个PostgreSQL数据库`mydb`。然后我们用函数构建一个引擎实例，如例1-2所示，你会发现我用了`postgresql+psycopg2`作为连接字符串的引擎和方言部分。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import create_engine\n",
    "engine = create_engine('postgresql+psycopg2://username:password@localhost:5432/mydb')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "同理，我们再看看MySQL引擎的创建，如例1-3所示，我们把参数`pool_recycle`设置成`3600`，表示每一小时自动连接一次。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import create_engine\n",
    "engine = create_engine('mysql+pymysql://cookiemonster:chocolatechip'\n",
    "                       '@mysql01.monster.internal/cookies', pool_recycle=3600)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">MySQL默认超过8小时空闲则断开连接。为了绕开这个问题，引擎设置`pool_recycle=3600`。\n",
    "\n",
    "`create_engine`函数的可选参数是：\n",
    "\n",
    "- `echo`：表示引擎行为的日志是否显示，像执行的SQL语句和其他参数等等。默认是`False`。\n",
    "- `ecoding`：默认使用SQLAlchemy的字符串编码`utf-8`，大多数DBAPI都用此编码。\n",
    "- `isolation_level`：SQLAlchemy分离等级。PostgreSQL+psycopg2的分类等级有`READ COMMITTED`，`READ UNCOMMITTED`，`REPEATABLE READ`，`SERIALIZABLE`，`AUTOCOMMIT`五种，默认是`READ COMMITTED`。PyMySQL也是这五种，InnoDB存储引擎数据库默认是`REPEATABLE READ`。\n",
    "    >用`isolation_level`关键词会为具体的DBAPI设置隔离等级，可就像数据库对应连接字符串的键值对一样，比如PostgreSQL是用psycopg2。\n",
    "- `pool_recycle`：这个参数是指数据库连接多少秒循环检查一次，对MySQL非常重要。默认值为`-1`，表示没有时间限制，一直连接。\n",
    "\n",
    "一旦引擎建立，我们就可以连接数据库了。通过`connect()`函数就可以。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "connection = engine.connect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们已经连接了数据库，可以用SQLAlchemy Core和ORM了。下面这部分，我们将探索SQLAlchemy Core的内容，学习如何定义和查询数据库。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# SQLAlchemy Core"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "连接数据库之后，我们就可以使用SQLAlchemy Core来进行数据库操作了。SQLAlchemy Core是用Pythonic方式的SQL表达式语言来表示SQL命令和数据结构的。SQLAlchemy Core具有的这种特性让它不仅可以用于Django或SQLAlchemy ORM，也可以单独使用。\n",
    "\n",
    "首先我们需要定义数据表的数据类型，数据的关联性以及其他约束条件。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# 2.Schema and Types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "为了搞定数据库，SQLAlchemy提供了以下三种方式来表示数据库中的表结构：\n",
    "- [Core](http://docs.sqlalchemy.org/en/rel_1_0/core/index.html)：自定义表`Table`对象\n",
    "- [ORM](http://docs.sqlalchemy.org/en/rel_1_0/orm/index.html)：用类`class`表示数据表\n",
    "- [SQLsoup](https://sqlsoup.readthedocs.org/en/latest/)和[Automap](http://docs.sqlalchemy.org/en/rel_1_0/orm/extensions/automap.html)：直接从数据库映射\n",
    "\n",
    "本章重点介绍第一种方式，即通过SQLAlchemy Core来实现，后面的章节会介绍其他两种方法。`Table`对象包括了一系列具有特定类型的列和属性，这些通过一个常用的元数据容器来控制。首先我们介绍SQLAlchemy建数据表的数据类型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Types\n",
    "\n",
    "SQLAlchemy有四种数据类型：\n",
    "\n",
    "- 通用类型（Generic）\n",
    "- SQL标准类型（SQL standard）\n",
    "- 数据库特有类型（Vendor Specific）\n",
    "- 用户自定义类型（User Defined）\n",
    "\n",
    "SQLAlchemy为不同的数据库定义了一些通用的数据类型。这些类型都在`sqlalchemy.types`模块中，为了引用方便也支持放在`sqlalchemy`里面。\n",
    "\n",
    "布尔型通用类型使用`BOOLEAN`SQL类型，对应的Python类型就是`True`和`False`；但是，对那些不支持`BOOLEAN`SQL类型的数据库通常要使用`SMALLINT`来代替。由于SQLAlchemy把这些细节都隐藏了，因此你可以放心大胆的操作数据，不用担心后面数据库用的是什么细节，只要在Python代码里处理`True`和`False`就行。即使数据仓库和交换数据库不一样，通用类型也可以完成数据处理。通用类型对应Python和SQL的含义如下表所示：\n",
    "\n",
    "| SQLAlchemy | Python | SQL |\n",
    "|:-:|:-:|:-:|\n",
    "| BigInteger | int | BIGINT |\n",
    "| Boolean | bool | BOOLEAN or SMALLINT |\n",
    "| Date | datetime.date | Date (SQLite: String) |\n",
    "| DateTime | datetime.datetime | DATETIME (SQLite: String) |\n",
    "| Enum | str | ENUM or VARCHAR |\n",
    "| Float | float or Decimal | FLOAT or REAL |\n",
    "| Integer | int | Integer |\n",
    "| Interval | datetime.timedelta | INTERVAL or DATE from epoch |\n",
    "| LargeBinary | byte | BLOB or BYTEA |\n",
    "| Numeric | decimal.Decimal | NUMERIC or DECIMAL |\n",
    "| Unicode | unicode | UNICODE or VARCHAR |\n",
    "| Text | str | CLOB or TEXT |\n",
    "| Time | datetime.time | DATETIME |\n",
    "\n",
    ">掌握通用类型非常重要，会经常使用\n",
    "\n",
    "如果通用类型不能满足需求，也会用到SQL标准类型和数据库专有类型。`CHAR`和`NVARCHAR`类型就是最好的例证，源自SQL类型。如果数据库的模式是在使用SQLAlchemy之前建立的，我们就要注意原模式与SQLAlchemy的差异。SQL标准类型的特性在不同的数据库里面可能有很大变化，也是在`sqlalchemy.types`模块中，为了和通用类型分开，都用大写字母表示。\n",
    "\n",
    "数据库专有类型只存在于特定的数据库中。你可以通过SQLALchemy网站或某种数据库的方言（dialect）文档查询此类型，放在`sqlalchemy.dialects`模块和数据库方言的子模块中，这些类型同样是大写字母。例如，我们想使用PostgreSQL强大的JSON类型，我们可以这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy.dialects.postgresql import JSON"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这样我们就可以用PostgreSQL特有的JSON函数为我们的应用定义JSON类型，比如`array_to_json`。\n",
    "\n",
    "你也可以根据自己的需要自定义类型。例如，当增加数据记录时，需要对即将存储到`VARCHAR`列的文本增加前缀，下一次从数据记录中获取这些记录的时候要重新去掉前缀。这样定义类型就可以给那些系统中已经存在的旧数据进行标识，表示这类数据在新应用中并没什么用或者不太重要。\n",
    "\n",
    "了解了四类数据类型之后，我们来看看如果用元数据组织数据库的结构。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "元数据用于把数据库结构集成在一起方便SQLAlchemy快速对接。可以把元数据看成是一种表目录，再加一些引擎和链接的信息。这些信息可以通过`MetaData.tables`查看。读操作是线程安全的，但是，表的建立不完全是线程安全的。元数据使用之前需要导入并初始化。下面让我们建立一个`Metadata`对象，为本章后面的例子建立容器来盛放数据库的信息目录。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import MetaData\n",
    "metadata = MetaData()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有了盛放数据库结构的地方，我们就可以建立数据表了。\n",
    "\n",
    "## Tables"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在SQLAlchemy Core里数据表对象初始化过程是通过`Table`通过表名称，元数据和数据列的名称，类型和属性共同构建，最终放入`MetaData`对象的。列对象表示数据表的每个字段，都是用包含名称、数据类型和一些SQL结构与约束特征的`Column`对象表示。我们将从这里开始建立一些数据表在SQLAlchemy Core部分使用。例2-1如下所示，建立一个网店的饼干库存表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Column('cookie_id', Integer(), table=<cookies>, primary_key=True, nullable=False),\n",
       " Column('cookie_name', String(length=50), table=<cookies>),\n",
       " Column('cookie_recipe_url', String(length=255), table=<cookies>),\n",
       " Column('quantity', Integer(), table=<cookies>),\n",
       " Column('unit_cost', Numeric(precision=12, scale=2), table=<cookies>)]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sqlalchemy import Table, Column, Integer, Numeric, String, ForeignKey\n",
    "\n",
    "cookies = Table('cookies', metadata,\n",
    "                Column('cookie_id', Integer(), primary_key=True),\n",
    "                Column('cookie_name', String(50), index=True),\n",
    "                Column('cookie_recipe_url', String(255)),\n",
    "                Column('quantity', Integer()),\n",
    "                Column('unit_cost', Numeric(12, 2))\n",
    "            \n",
    ")\n",
    "\n",
    "list(cookies.columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "建立新表之前，我们需要理解表的基础单元——列。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Columns"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "列定义了数据表中的字段，它们通过我们对其关键词参数的设置来表达具体的含义。不同类型的主要参数不同。例如，字符串类型的基本参数是长度，而带小数的数值类型基本参数是精度和长度。其他类型大都没有基本参数。\n",
    "\n",
    ">有时你也会看到字符串类型没有设置长度。并非所有的数据库都支持这种特性，包括MySQL也不支持。\n",
    "\n",
    "列也有一些别的参数来帮助它们建立更丰富的特性。我们可以为列设置是否允许空值或必须具有唯一性（`unique`）。还可以定义初始值（`default`），通常这么做是为了日志记录或财务审计的需要，如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[Column('user_id', Integer(), table=<users>, primary_key=True, nullable=False),\n",
       " Column('username', String(length=15), table=<users>, nullable=False),\n",
       " Column('email_address', String(length=255), table=<users>, nullable=False),\n",
       " Column('phone', String(length=20), table=<users>, nullable=False),\n",
       " Column('password', String(length=25), table=<users>, nullable=False),\n",
       " Column('created_on', DateTime(), table=<users>, default=ColumnDefault(<function ColumnDefault._maybe_wrap_callable.<locals>.<lambda> at 0x0000000005AD3730>)),\n",
       " Column('updated_on', DateTime(), table=<users>, onupdate=ColumnDefault(<function ColumnDefault._maybe_wrap_callable.<locals>.<lambda> at 0x0000000005AD3950>), default=ColumnDefault(<function ColumnDefault._maybe_wrap_callable.<locals>.<lambda> at 0x0000000005AD38C8>))]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from datetime import datetime\n",
    "from sqlalchemy import DateTime\n",
    "users = Table('users', metadata,\n",
    "                Column('user_id', Integer(), primary_key=True),\n",
    "                Column('username', String(15), nullable=False, unique=True),\n",
    "                Column('email_address', String(255), nullable=False),\n",
    "                Column('phone', String(20), nullable=False),\n",
    "                Column('password', String(25), nullable=False),\n",
    "                Column('created_on', DateTime(), default=datetime.now),\n",
    "                Column('updated_on', DateTime(), default=datetime.now, onupdate=datetime.now)\n",
    ")\n",
    "\n",
    "list(users.columns)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">你会发现这里使用`datatime.now`，而不是`datatime.now()`。如果我们直接用函数，那么时间可能就是数据表第一次建立的时间。不带`()`我们就可以在每条记录生成时产生一个新的时间。\n",
    "\n",
    "我们通过列关键词参数定义了数据表的结构和约束；但是，列对象有时可能需要和其他表进行关联。当你处理数据库时，你必须告诉SQLAlchemy关于这个数据库内部的模式，结构和约束。假如有一个数据库和SQLAlchemy使用的索引名称模式不同，那么你必须定义索引才能正常使用。下面两个小节将告诉你怎么做。\n",
    "\n",
    ">*Keys and Constraints*和*Index*两节的程序其实都可以在`Table`构造函数里直接实现，也可以通过特定方法在表建立之后实现，再增加到表中。它们都会作为单独一行语句保存到`metadata`里面。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Keys and Constraints\n",
    "\n",
    "键和约束是用来保证数据在存到数据库之前能够满足一些约束条件的方法。表示键和约束的对象在SQLAlchemy模块里面都有，常用的三个如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import PrimaryKeyConstraint, UniqueConstraint, CheckConstraint"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "主键是最常用的，表示数据表中一条记录的唯一标识，可以用来保证不同表里相关数据之间正确的关系。前面的例1和例2中，我们用`primary_key`参数将一列设置为主键。你还可以用若干列构成的元组来定义一个复合主键。这个键在表中被看成是一个内容为元组的列，会按照它们原始顺序进行排列。主键还可以在表构建之后再定义，如下所示。你可以用逗号分隔，增加多列形成一个复合主键。如果我们想在上面例2中显示定义主键，可以这样做："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "PrimaryKeyConstraint('user_id', name='user_pk')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "另一个常用的约束就是唯一性约束，确保一个字段里任意两个值不重复，如果在登录系统里面出现两个用户名是一样的，那就麻烦了。我们也可以用下面的方式定义例2中用户名列的唯一性约束："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "UniqueConstraint('username', name='uix_username')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "例2里没有用到检查约束类型。这种约束类型是用来保证一列数据与用户定义的条件一致。下面的例子，我们保证`unit_cost`列永远非负，因为成本不可能小于0。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "CheckConstraint('unit_coust >= 0.00', name='unit_coust_positive')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "除了键和约束，我们还想更高效的查询一些字段。这就要介绍索引（Indexes）。\n",
    "\n",
    "### Indexes\n",
    "\n",
    "索引是用来加速查询的，在例1里面，我们把`cookie_name`加上了索引，因为我们知道我们经常需要查询它们。索引创建之后你就会获得一个`ix_cookies_cookie_name`索引。我们也可以显式定义一个索引。多列的索引可以通过分号分隔名称来建立。你还可以增加一个参数`unique=True`来保证索引具有唯一性。如果显式声明索引，它们就会在放在对应列后面。下面的做法与例1相同："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import Index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "Index('ix_cookies_cookie_name', 'cookie_name')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们还可以创建了函数索引，不同的数据库可能用法上会有点儿变化。这样可以让你为一些经常查询不常用信息的需求创建检索。例如，如果你想从饼干的SKU号和名称的组合中找`SKU0001 Chocolate Chip`信息。我们就可以建立一个复合索引来查询："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "Index('ix_test', mytable.c.cookie_sku, mytable.c.cookie_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面到了关系型数据库最重要的部分了，就是表的关联关系与定义。\n",
    "\n",
    "### Relationships and ForeignKeyConstraints\n",
    "\n",
    "现在我们有了一个约束和索引都正确的表，让我们看看表之间的关系如何建立。我们需要一种方法来跟踪订单，包括记录已销售的饼干和数量的信息。表关系图如下所示：\n",
    "![](relationship.png)\n",
    "例3实现了`line_items`表`order_id`列的关系，就是用`ForeignKeyConstraint`定义两个表的关系。在本例中，我们有很多`line_items`表示单个订单。但是，如果你深入到这些订单中，你会发现订单与`cookies`表的`cookie_id`外键有关联关系。这是因为`line_items`表其实与`orders`和`cookies`表的一些数据都有关联。关联表用来表示另外两个表之间的多对多关系。通常一个外键用来表示一对多关系，但是如果一个表有多个外键，那么这个表很可能是一个关联表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import ForeignKey, Boolean\n",
    "orders = Table('orders', metadata,\n",
    "            Column('order_id', Integer(), primary_key=True),\n",
    "            Column('user_id', ForeignKey('users.user_id')),\n",
    "            Column('shipped', Boolean(), default=False)\n",
    ")\n",
    "line_items = Table('line_items', metadata,\n",
    "                Column('line_items_id', Integer(), primary_key=True),\n",
    "                Column('order_id', ForeignKey('orders.order_id')),\n",
    "                Column('cookie_id', ForeignKey('cookies.cookie_id')),\n",
    "                Column('quantity', Integer()),\n",
    "                Column('extended_cost', Numeric(12, 2))\n",
    ")                   "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用字符串替换实际的列名可以在多个模块中把表的定义分离，这样就不用担心表加载的顺序了。这是因为，它只会在首次连接表名称和列名称的时候解析字符串执行表查询。如果我们直接用表引用，比如`cookies.c.cookie_id`，我们的外键在每次模块初始化的时候都要执行一次，如果表加载的顺序特别靠后就会出错。\n",
    "\n",
    "你可以显式的调研`ForeignKeyConstraint`定义，在SQLAlchemy里面可以对已经建好的表建立外键，就像其他的键，约束和索引的创建一样。需要先倒入`ForeignKeyConstraint`模块然后定义。下面的代码是创建一个`ForeignKeyConstraint`表示`line_items`表和`orders`之间`order_id`外键。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import ForeignKeyConstraint\n",
    "\n",
    "ForeignKeyConstraint(['order_id'], ['orders.order_id'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "前面做的每件事情都是用SQLAlchemy可以理解的方式定义的。如果你的数据库已经存在，而且schema已经建立，你就可以进行查询了。如果你还没建立，下面就介绍如何把数据库建成文件。\n",
    "\n",
    "### Persisting the Tables\n",
    "\n",
    "表和模式定义与原数据相关。把模式保存到数据库很简单，用`metadata`的`create_all()`方法就可以了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "metadata.create_all(engine)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认情况下，`create_all()`方法不会重新创建已经存在的数据库，所有运行多次也很安全。相比直接在应用代码里修改数据库，用Alembic那样的迁移工具处理数据库的更新或其他模式是更好的方法。我们将在后面的章节里介绍。现在数据库里面已经有表了，这一章完整的代码如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String,\n",
    "                        Boolean, DateTime, ForeignKey, create_engine)\n",
    "metadata = MetaData()\n",
    "cookies = Table('cookies', metadata,\n",
    "                Column('cookie_id', Integer(), primary_key=True),\n",
    "                Column('cookie_name', String(50), index=True),\n",
    "                Column('cookie_recipe_url', String(255)),\n",
    "                Column('cookie_sku', String(55)),\n",
    "                Column('quantity', Integer()),\n",
    "                Column('unit_cost', Numeric(12, 2))\n",
    "                )\n",
    "users = Table('users', metadata,\n",
    "              Column('user_id', Integer(), primary_key=True),\n",
    "              Column('customer_number', Integer(), autoincrement=True),\n",
    "              Column('username', String(15), nullable=False, unique=True),\n",
    "              Column('email_address', String(255), nullable=False),\n",
    "              Column('phone', String(20), nullable=False),\n",
    "              Column('password', String(25), nullable=False),\n",
    "              Column('created_on', DateTime(), default=datetime.now),\n",
    "              Column('updated_on', DateTime(),\n",
    "                     default=datetime.now, onupdate=datetime.now)\n",
    "              )\n",
    "orders = Table('orders', metadata,\n",
    "               Column('order_id', Integer(), primary_key=True),\n",
    "               Column('user_id', ForeignKey('users.user_id')),\n",
    "               Column('shipped', Boolean(), default=False)\n",
    "               )\n",
    "line_items = Table('line_items', metadata,\n",
    "                   Column('line_items_id', Integer(), primary_key=True),\n",
    "                   Column('order_id', ForeignKey('orders.order_id')),\n",
    "                   Column('cookie_id', ForeignKey('cookies.cookie_id')),\n",
    "                   Column('quantity', Integer()),\n",
    "                   Column('extended_cost', Numeric(12, 2))\n",
    "                   )\n",
    "engine = create_engine('sqlite:///:memory:')\n",
    "metadata.create_all(engine)\n",
    "connection = engine.connect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "本章我们介绍了如何在SQLAlchemy里把元数据当作目录（catalog）来存放表模式和其他数据。我们还定义了带有多列和多约束的表。然后，我们介绍约束的类型和这些约束对列进行的显式定义的方法。其次，我们介绍了默认值的设置和为了查账进行更新值的方法。最后，我们介绍了把模式保存到数据库进行重用的方法。下面我们介绍如何在模式中用SQL表达式语言进行数据的操作。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "#  3.SQLAlchemy Core数据操作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "现在数据库里面有了表，让我们来操作它们。首先我们将演示如何增删改查，然后介绍如果排序，组合以及如何使用关系。我们用SQLAlchemy Core提供的SEL（SQL表达式语言）演示。还是用上一章建立的数据库，首先我们看看如何新建数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## Inserting Data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "首先，我们在`cookies`表新建一行我最喜欢的饼干（巧克力味的）。用`cookies`表的`insert()`方法，然后在`values()`语句里面设置各个列的值就可以了。如下所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INSERT INTO cookies (cookie_name, cookie_recipe_url, cookie_sku, quantity, unit_cost) VALUES (:cookie_name, :cookie_recipe_url, :cookie_sku, :quantity, :unit_cost)\n"
     ]
    }
   ],
   "source": [
    "ins = cookies.insert().values(\n",
    "    cookie_name=\"chocolate chip\",\n",
    "    cookie_recipe_url=\"http://some.aweso.me/cookie/recipe.html\",\n",
    "    cookie_sku=\"CC01\",\n",
    "    quantity=\"12\",\n",
    "    unit_cost=\"0.50\"\n",
    ")\n",
    "print(str(ins))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面显示了对应的SQL语句。每一列的值都用`:column_name`代替了，SQLAlchemy的`str()`函数就是这样显示的。数值都进行过清洗和转义处理，保证数据安全，避免SQL注入攻击。因为不同种类的数据库处理参数值的方言可能有点差别，所以通过编译版本的语句可以看到输入的内容。`ins`对象的`compile()`方法会返回一个SQLAlchemy对象，通过`params`属性就可以看到数值了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'cookie_name': 'chocolate chip',\n",
       " 'cookie_recipe_url': 'http://some.aweso.me/cookie/recipe.html',\n",
       " 'cookie_sku': 'CC01',\n",
       " 'quantity': '12',\n",
       " 'unit_cost': '0.50'}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ins.compile().params"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "`ins.compile()`通过方言编译数据，但是并没执行，因此我们需要用`params`属性查看。\n",
    "\n",
    "介绍了新建语句的用法之后，我们用`connection`的`execute()`方法把数据加入数据表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "result = connection.execute(ins)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "我们还可以用`inserted_primary_key`属性查看刚刚新建数据的ID号。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result.inserted_primary_key"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "我们简单介绍一下`excute()`执行的过程。当我们建立前面那条SQL表达式语言的插入语句时，实际上是创建了一个可以快速向下遍历的树状结构。当我们调用`excute()`方法时，它把刚刚传入的语句和其他任何参数一起编译成对应数据库方言编译器能够识别的语句。编译器通过遍历那个树状结构建成一个普通的SQL语句。这个语句返回到`excute()`方法，`excute()`方法通过绑定的连接把语句传递到数据库。数据库服务器就执行SQL语句然后把结果返回给`excute()`方法。\n",
    "\n",
    "`insert`除了可以作为表对象的实例方法，也可以当作顶层函数使用，这样可以把表对象作为参数，更具灵活性。例如，假如公司的两个部门分别拥有相互独立的库存数据，就可以按照例3-3的形式再插入一行数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import insert\n",
    "ins = insert(cookies).values(\n",
    "    cookie_name=\"chocolate chip\",\n",
    "    cookie_recipe_url=\"http://some.aweso.me/cookie/recipe.html\",\n",
    "    cookie_sku=\"CC01\",\n",
    "    quantity=\"12\",\n",
    "    unit_cost=\"0.50\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">虽然`insert`的表对象方法和更具一般性的函数两种形式结果一样，我还是更喜欢后者，因为它更接近SQL语句的用法。\n",
    "\n",
    "连接对象的`execute()`方法不仅仅只是处理语句，还可以把`values`当作`execute()`方法的参数。当语句被编译时，它会把每个关键词参数的键增加到字段列表中，然后再把每个字段对应的值增加到SQL语句的`VALUE`参数里。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2]"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ins = cookies.insert()\n",
    "result = connection.execute(\n",
    "    ins,\n",
    "    cookie_name='dark chocolate chip',\n",
    "    cookie_recipe_url='http://some.aweso.me/cookie/recipe_dark.html',\n",
    "    cookie_sku='CC02',\n",
    "    quantity='1',\n",
    "    unit_cost='0.75'\n",
    ")\n",
    "result.inserted_primary_key"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "不过这种形式并不常用，但是，它为语句在传到数据库服务器之前的编译和组织方式提供了一个很好的解释。我们可以用放了字段和数值词典的列表一次性插入多个记录。让我们把两种饼干的库存数据插入`cookies`表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ins = cookies.insert()\n",
    "inventory_list = [\n",
    "    {\n",
    "        'cookie_name': 'peanut butter',\n",
    "        'cookie_recipe_url': 'http://some.aweso.me/cookie/peanut.html',\n",
    "        'cookie_sku': 'PB01',\n",
    "        'quantity': '24',\n",
    "        'unit_cost': '0.25'\n",
    "    },\n",
    "    {\n",
    "        'cookie_name': 'oatmeal raisin',\n",
    "        'cookie_recipe_url': 'http://some.okay.me/cookie/raisin.html',\n",
    "        'cookie_sku': 'EWW01',\n",
    "        'quantity': '100',\n",
    "        'unit_cost': '1.00'\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, inventory_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">列表中的每个词典都要有同样的键（`keys`）。首先方言编译器会编译第一个词典的语句内容，如果后面词典的键与第一条不同就会失败，因为第一条的字段已经建好了。\n",
    "\n",
    "现在有了数据，我们就可以查询了。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Querying Data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Miniconda3\\lib\\site-packages\\sqlalchemy\\sql\\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
      "  'storage.' % (dialect.name, dialect.driver))\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[(1, 'chocolate chip', 'http://some.aweso.me/cookie/recipe.html', 'CC01', 12, Decimal('0.50')),\n",
       " (2, 'dark chocolate chip', 'http://some.aweso.me/cookie/recipe_dark.html', 'CC02', 1, Decimal('0.75')),\n",
       " (3, 'peanut butter', 'http://some.aweso.me/cookie/peanut.html', 'PB01', 24, Decimal('0.25')),\n",
       " (4, 'oatmeal raisin', 'http://some.okay.me/cookie/raisin.html', 'EWW01', 100, Decimal('1.00'))]"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sqlalchemy.sql import select\n",
    "s = select([cookies])\n",
    "rp = connection.execute(s)\n",
    "results = rp.fetchall()\n",
    "results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT cookies.cookie_id, cookies.cookie_name, cookies.cookie_recipe_url, cookies.cookie_sku, cookies.quantity, cookies.unit_cost \n",
      "FROM cookies\n"
     ]
    }
   ],
   "source": [
    "print(str(s))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "和`insert`用法类似，`select`也是既可以作为表对象的实例方法，也可以作为更具一般性的顶层函数使用。我更喜欢顶层函数的使用方式，因为和SQL用法一样。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(1, 'chocolate chip', 'http://some.aweso.me/cookie/recipe.html', 'CC01', 12, Decimal('0.50')),\n",
       " (2, 'dark chocolate chip', 'http://some.aweso.me/cookie/recipe_dark.html', 'CC02', 1, Decimal('0.75')),\n",
       " (3, 'peanut butter', 'http://some.aweso.me/cookie/peanut.html', 'PB01', 24, Decimal('0.25')),\n",
       " (4, 'oatmeal raisin', 'http://some.okay.me/cookie/raisin.html', 'EWW01', 100, Decimal('1.00'))]"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sqlalchemy.sql import select\n",
    "s = cookies.select()\n",
    "rp = connection.execute(s)\n",
    "results = rp.fetchall()\n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### ResultProxy"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "ResultProxy是对数据库API光标对象的封装，其主要目的是让数据操作更简单。例如，它可以通过索引，字段名称和列对象让查询操作更简单，演示如例3-8所示。任何一种方法查询数据都很简单。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "first_row = results[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'chocolate chip'"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_row[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'chocolate chip'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_row.cookie_name"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'chocolate chip'"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "first_row[cookies.c.cookie_name]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的输出结果都是`results`变量第一个记录的数据`chocolate chip`。接入灵活只是ResultProxy能力的一部分。我们还可以用ResultProxy实现循环。例如，我们可以打印所有饼干的名称。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chocolate chip\n",
      "dark chocolate chip\n",
      "peanut butter\n",
      "oatmeal raisin\n"
     ]
    }
   ],
   "source": [
    "rp = connection.execute(s)\n",
    "for record in rp:\n",
    "    print(record.cookie_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "ResultProxy除了可以循环，或调用`fetchall()`方法之外，很多其他数据接入方式也可以用。其实，上例中所有的`result`变量所有的插入数据操作都是用ResultProxy实现的。`rowcount()`和`inserted_primary_key()`方法也是ResultProxy获取信息的一种方式。你也可以用下面的方法获取信息：\n",
    "- first()——如果存在则返回第一条记录并关闭连接\n",
    "- fetchone()——返回一条记录，光标继续开着，等待新的查询\n",
    "- scalar()——如果查询结果只有一行一列，就返回一个值\n",
    "\n",
    "如果要看结果中所有列名，可以用`keys()`方法。后面的章节里，我们还会经常使用`first`，`scalar`，`fetchone`，`fetchall`方法和ResultProxy循环。\n",
    "> 产品代码\n",
    "> 写产品代码的时候，我有几条原则：\n",
    "> - 用`first`获取一条记录，不用`scalar`和`fetchone`，因为这样更清晰\n",
    "> - 用ResultProxy循环，不用`fetchall`和`fetchone`方法。这样内存开销更新，因为通常我们都是一次处理一条记录\n",
    "> - 尽量不要用`fetchone`，因为它会让连接一直开着\n",
    "> - `scalar`也要少用，因为当查询返回多余一行一列数据的时候容易出错，这一点在测试的时候经常被忽略\n",
    "\n",
    "在上例中，每一次我们查询数据集的时候每条记录的所有列都会返回。而通常我们只需要一部分列就可以。如果数据非常大，这样查询就会非常耗费内存，查询速度就会很慢。SQLAlchemy不会为查询或ResultProxy增加负担；但是，通常查询完成后，你需要看看查询是否消耗了太多内存。下面我们就来介绍如何控制查询的范围。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 控制查询的列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "可以用`select()`方法将要查询的列以列表形式放入。例如，下面代码是只需要查看饼干的名称和质量时的操作。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['cookie_name', 'quantity']\n"
     ]
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "rp = connection.execute(s)\n",
    "print(rp.keys())\n",
    "result = rp.first()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('chocolate chip', 12)"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "这样我们就建立了简单的`select`语句，我们将看看其他改变选择结果的操作。首先我们看看如何改变顺序。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "#### Ordering"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "如果在上面例10中你要查看所有的数据结果，你会发现名称排序很混乱。但是，如果我们想让名称按照指定顺序排列，可用`select`的`order_by()`语句。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 - dark chocolate chip\n",
      "12 - chocolate chip\n",
      "24 - peanut butter\n",
      "100 - oatmeal raisin\n"
     ]
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "s = s.order_by(cookies.c.quantity)\n",
    "rp = connection.execute(s)\n",
    "for cookie in rp:\n",
    "    print('{} - {}'.format(cookie.quantity, cookie.cookie_name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "如果要逆序排列，就在`order_by()`里面增加`desc()`。用`desc()`包裹排序参数即可。\n",
    "> `desc()`也可以当成列对象的方法来使用，"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100 - oatmeal raisin\n",
      "24 - peanut butter\n",
      "12 - chocolate chip\n",
      "1 - dark chocolate chip\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import desc\n",
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "s = s.order_by(desc(cookies.c.quantity))\n",
    "rp = connection.execute(s)\n",
    "for cookie in rp:\n",
    "    print('{} - {}'.format(cookie.quantity, cookie.cookie_name))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "还可以限制查询记录结果的数量。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "#### Limiting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "前面的例子里，`first()`和`fetchone()`方法是用来获得一行记录的。ResultProxy可以提供一行数据，实际中我们经常需要多行数据。如果我们想限制查询数量，我们可以用`limit()`函数。例如，如果我现在想做销量最好的两种饼干，那么对排序后的查询增加一个限制条件就可以了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['dark chocolate chip', 'chocolate chip']\n"
     ]
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "s = s.order_by(cookies.c.quantity)\n",
    "s = s.limit(2)\n",
    "rp = connection.execute(s)\n",
    "print([result.cookie_name for result in rp])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们知道饼干的种类了，我开始关心库存还有多少。很多数据库都有一堆SQL函数对数据进行统计，必然SUM等等，让我们看看这些函数如何使用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Builtin SQL Functions and Labels"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "SQLAlchemy的SQL函数里最常用的是`SUM()`和`COUNT()`。使用这个函数之前我们需要导入`sqlalchemy.sql.func`模块，这些函数只要包裹列对象就可以运行。所以要统计饼干的总量，我们可以这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "137\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import func\n",
    "s = select([func.sum(cookies.c.quantity)])\n",
    "rp = connection.execute(s)\n",
    "print(rp.scalar())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">因为Python内置函数也有`sum`，所以使用SQLAlchemy的`sum`时，建议导入`func`用`func.sum`。\n",
    "\n",
    "现在让我们用`count`函数统计`cookie`表里有多少条库存记录。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['count_1']\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "s = select([func.count(cookies.c.quantity)])\n",
    "rp = connection.execute(s)\n",
    "record = rp.first()\n",
    "print(record.keys()) # 显示Resultproxy里的列\n",
    "print(record.count_1) # 列名是自动生成的，命名方式是`<函数名>_<位置>`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这个列名有点隐蔽。如果我们想自定义名称，也可以用在`count()`函数后用`label()`函数来定义列名。例如，我们想用更好记的名称来定义记录数量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['inventory_count']\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "s = select([func.count(cookies.c.cookie_name).label('inventory_count')])\n",
    "rp = connection.execute(s)\n",
    "record = rp.first()\n",
    "print(record.keys())\n",
    "print(record.inventory_count)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "介绍了如何限制行和列的数量之后，我们再看看如何进行数据过滤。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Filtering"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "过滤查询和SQL一样用`where()`函数来实现。通常`where()`函数有一个列名称，一个操作符和一个值或列。也可以用连接多个`where()`语句，像SQL里面逻辑操作符`AND`的作用。下面我们来找名称为`chocolate chip`的饼干。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('cookie_id', 1),\n",
       " ('cookie_name', 'chocolate chip'),\n",
       " ('cookie_recipe_url', 'http://some.aweso.me/cookie/recipe.html'),\n",
       " ('cookie_sku', 'CC01'),\n",
       " ('quantity', 12),\n",
       " ('unit_cost', Decimal('0.50'))]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies]).where(cookies.c.cookie_name == 'chocolate chip')\n",
    "rp = connection.execute(s)\n",
    "record = rp.first()\n",
    "record.items() # 显示所有列名和数值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们还可以用`where()`找包含`chocolate`的饼干名称。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chocolate chip\n",
      "dark chocolate chip\n"
     ]
    }
   ],
   "source": [
    "s = select([cookies]).where(cookies.c.cookie_name.like('%chocolate%'))\n",
    "rp = connection.execute(s)\n",
    "for record in rp.fetchall():\n",
    "    print(record.cookie_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`where()`语句里我们用`cookies.c.cookie_name`作为过滤的`ClauseElement`类型。我们现在停下来，看看`ClauseElement`类型的其他功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Operators\n",
    "\n",
    "ClauseElements就是我们在从句中使用的一个元素，通常都是数据表的列；但是，和列不同，ClauseElements有许多功能。在例3-18里面，我们用来`like()`方法，其实还有很多方法如表3-1所示。每个方法都和标准SQL里面的函数类似。后面会大量使用它们。\n",
    "\n",
    "|方法|目的|\n",
    "|:-:|:-:|\n",
    "|`between(cleft, cright)` | Find where the column is between cleft and cright|\n",
    "|`concat(column_two)` | Concatenate column with column_two|\n",
    "|`distinct()` | Find only unique values for column|\n",
    "|`in_([list])` | Find where the column is in the list|\n",
    "|`is_(None)` | Find where the column is None (commonly used for Null checks with None)|\n",
    "|`contains(string)` | Find where the column has string in it (Case-sensitive)|\n",
    "|`endswith(string)` | Find where the column ends with string (Case-sensitive)|\n",
    "|`like(string)` | Find where the column is like string (Case-sensitive)|\n",
    "|`startswith(string)` | Find where the column begins with string (Case-sensitive)|\n",
    "|`ilike(string)` | Find where the column is like string (NOT Case-sensitive)|\n",
    "\n",
    "还有两个相反操作的函数`notlike()`和`notin_()`，以及一个不带下划线的函数`isnot()`。\n",
    "\n",
    "如果我们不用这些方法，我们还可以用运算符。大部分运算符都和你的习惯一样，不过我们要介绍一些奇怪的地方。\n",
    "\n",
    "#### 操作符\n",
    "\n",
    "到目前为止我们过滤数据都是通过判断列是否等于一个数值，或者用ClauseElement方法的函数，比如`like()`；其实我们还可以用很多运算符号来过滤数据。SQLAlchemy提供了大量Python的标准运算符。这包括所有的标准比较运算符（`==`，`!=`，`<`，`>`，`>=`），与Python语句里使用方法一致。`==`操作符在和`None`比较时还表示`IS NULL`。算法运算符（`+`,`-`,`*`,`/`,`%`）也可用于数据库字符串处理，如例3-19所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('chocolate chip', 'SKU-CC01')\n",
      "('dark chocolate chip', 'SKU-CC02')\n",
      "('peanut butter', 'SKU-PB01')\n",
      "('oatmeal raisin', 'SKU-EWW01')\n"
     ]
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, 'SKU-' + cookies.c.cookie_sku])\n",
    "for row in connection.execute(s):\n",
    "    print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "另一个常用操作就是计算多列的数值。通常做财务和统计报表时经常用到，例3-20计算库存金额："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chocolate chip - 6.00\n",
      "dark chocolate chip - 0.75\n",
      "peanut butter - 6.00\n",
      "oatmeal raisin - 100.00\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Miniconda3\\lib\\site-packages\\sqlalchemy\\sql\\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
      "  'storage.' % (dialect.name, dialect.driver))\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import cast\n",
    "s = select([cookies.c.cookie_name,\n",
    "            cast((cookies.c.quantity * cookies.c.unit_cost),\n",
    "                 Numeric(12,2)).label('inv_cost')])\n",
    "for row in connection.execute(s):\n",
    "    print('{} - {}'.format(row.cookie_name, row.inv_cost))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Boolean Operators\n",
    "\n",
    "SQLAlchemy也支持逻辑运算符（与AND，或OR，非NOT），用位操作符表示（`&`，`|`，`~`）。使用时一定要注意，因为Python自带的逻辑运算符规则。比如，`&`比`<`优先级高，当你写`A < B & C < D`的时候，运算结果是`A < (B & C) < D`，而你实际想写的是`(A < B) & (C < D)`。为了清晰表达意思，请用连接词（conjunctions），不要用这些重载运算符。\n",
    "\n",
    "通常在处理多个从句时，从句之间存在与或非关系时，应该用连接词。\n",
    "\n",
    "#### Conjunctions\n",
    "\n",
    "虽然可以把多个`where()`从句连起来，但是用连接词会让语句更清晰好看。SQLAlchemy的连接词是`and_()`，`or_()`和`not_()`。如果我们想要查询库存和单价满足特定条件的饼干时，可以用`and_()`实现。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "peanut butter\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import and_, or_, not_\n",
    "s = select([cookies]).where(\n",
    "    and_(\n",
    "        cookies.c.quantity > 23,\n",
    "        cookies.c.unit_cost < 0.40\n",
    "    )\n",
    ")\n",
    "for row in connection.execute(s):\n",
    "    print(row.cookie_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`or_()`函数与`and_()`相反，包含任何一种情形就可以。如果我们想找到库存在10到50之间，或名称包含*chip*的饼干时，可以用`or_`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "chocolate chip\n",
      "dark chocolate chip\n",
      "peanut butter\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import and_, or_, not_\n",
    "s = select([cookies]).where(\n",
    "    or_(\n",
    "        cookies.c.quantity.between(10, 50),\n",
    "        cookies.c.cookie_name.contains('chip')\n",
    "    )\n",
    ")\n",
    "for row in connection.execute(s):\n",
    "    print(row.cookie_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`not()`连接词类似，只是表示不包含条件的结果。到这里我们已经可以轻松的查询数据了，下面我们看看如何更新数据。\n",
    "\n",
    "### Updating Data\n",
    "\n",
    "还有一个数据更新方法，和前面用的`insert`方法类似，除了它们需要指定一个条件表面要更新的行，语法与`insert`完全一致。更新方法可以用`update()`函数或待更新表的`update()`方法。如果不增加条件，就会更新表中所有行。当我做完新的饼干之后，就要更新库存数据。在例3-23中，我们更新对应饼干的库存，然后计算新的总库存量。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "           cookie_id: 1\n",
      "         cookie_name: chocolate chip\n",
      "   cookie_recipe_url: http://some.aweso.me/cookie/recipe.html\n",
      "          cookie_sku: CC01\n",
      "            quantity: 132\n",
      "           unit_cost: 0.50\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import update\n",
    "u = update(cookies).where(cookies.c.cookie_name == 'chocolate chip')\n",
    "u = u.values(quantity=(cookies.c.quantity + 120))\n",
    "result = connection.execute(u)\n",
    "print(result.rowcount)\n",
    "\n",
    "s = select([cookies]).where(cookies.c.cookie_name == \"chocolate chip\")\n",
    "result = connection.execute(s).first()\n",
    "for key in result.keys():\n",
    "    print('{:>20}: {}'.format(key, result[key]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "除了更新数据，还要删除数据。\n",
    "\n",
    "### Deleting Data\n",
    "\n",
    "删除数据可以用`delete()`函数或表的`delete()`方法。和`insert()`，`update()`不同的是，`delete()`无数值参数，只有一个可选的`where()`用于设置删除区域（如果没有就删除全表所有数据）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "0\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import delete\n",
    "\n",
    "u = delete(cookies).where(cookies.c.cookie_name == 'dark chocolate chip')\n",
    "result = connection.execute(u)\n",
    "print(result.rowcount)\n",
    "\n",
    "s = select([cookies]).where(cookies.c.cookie_name == \"dark chocolate chip\")\n",
    "result = connection.execute(s).fetchall()\n",
    "print(len(result))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在让我们回想一下所学的知识，对`users`，`orders`，`line_items`表进行更新。你可以直接复制代码，但是建议你试试其他方法新建数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "customer_list = [\n",
    "    {\n",
    "        'username': 'cookiemon',\n",
    "        'email_address': 'mon@cookie.com',\n",
    "        'phone': '111-111-1111',\n",
    "        'password': 'password'\n",
    "    },\n",
    "    {\n",
    "        'username': 'cakeeater',\n",
    "        'email_address': 'cakeeater@cake.com',\n",
    "        'phone': '222-222-2222',\n",
    "        'password': 'password'\n",
    "    },\n",
    "    {\n",
    "        'username': 'pieguy',\n",
    "        'email_address': 'guy@pie.com',\n",
    "        'phone': '333-333-3333',\n",
    "        'password': 'password'\n",
    "    }\n",
    "]\n",
    "ins = users.insert()\n",
    "result = connection.execute(ins, customer_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "有了用户数据，让我们再更新他们的`orders`，`line_items`表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import insert\n",
    "ins = insert(orders).values(user_id=1, order_id=1)\n",
    "result = connection.execute(ins)\n",
    "ins = insert(line_items)\n",
    "order_items = [\n",
    "    {\n",
    "        'order_id': 1,\n",
    "        'cookie_id': 1,\n",
    "        'quantity': 2,\n",
    "        'extended_cost': 1.00\n",
    "    },\n",
    "    {\n",
    "        'order_id': 1,\n",
    "        'cookie_id': 3,\n",
    "        'quantity': 12,\n",
    "        'extended_cost': 3.00\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, order_items)\n",
    "\n",
    "ins = insert(orders).values(user_id=2, order_id=2)\n",
    "result = connection.execute(ins)\n",
    "ins = insert(line_items)\n",
    "order_items = [\n",
    "    {\n",
    "        'order_id': 2,\n",
    "        'cookie_id': 1,\n",
    "        'quantity': 24,\n",
    "        'extended_cost': 12.00\n",
    "    },\n",
    "    {\n",
    "        'order_id': 2,\n",
    "        'cookie_id': 4,\n",
    "        'quantity': 6,\n",
    "        'extended_cost': 6.00\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, order_items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在SQLAlchemy Core的第二章中我们介绍过外键和关系；但是我们还没有用它们做过查询，下面我们就来看看这些关系。\n",
    "\n",
    "### Joins"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用`join()`和`outerjoin()`方法进行数据关联。例如，发货之前需要了解用户`cookiemon`订购了那种饼干。这就需要用3个`join`来汇总三张表的数据。另外，当用多个`join`汇总数据时，你可能需要重新组织`from`后面`join`关联内容的顺序，SQLAlchemy提供了`select_from`来实现这个功能。通过`select_from`我们可以将整个`from`从句替换成SQLAlchemy支持的形式。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 'cookiemon', '111-111-1111', 'chocolate chip', 2, Decimal('1.00'))\n",
      "(1, 'cookiemon', '111-111-1111', 'peanut butter', 12, Decimal('3.00'))\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "d:\\Miniconda3\\lib\\site-packages\\sqlalchemy\\sql\\sqltypes.py:565: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal numbers as strings or integers on this platform for lossless storage.\n",
      "  'storage.' % (dialect.name, dialect.driver))\n"
     ]
    }
   ],
   "source": [
    "columns = [orders.c.order_id, users.c.username, users.c.phone,\n",
    "            cookies.c.cookie_name, line_items.c.quantity,\n",
    "            line_items.c.extended_cost]\n",
    "cookiemon_orders = select(columns)\n",
    "cookiemon_orders = cookiemon_orders.select_from(orders.join(users).join(\n",
    "                    line_items).join(cookies)).where(users.c.username ==\n",
    "                    'cookiemon')\n",
    "result = connection.execute(cookiemon_orders).fetchall()\n",
    "for row in result:\n",
    "    print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的SQL语句是这样："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT orders.order_id, users.username, users.phone, cookies.cookie_name, line_items.quantity, line_items.extended_cost \n",
      "FROM orders JOIN users ON users.user_id = orders.user_id JOIN line_items ON orders.order_id = line_items.order_id JOIN cookies ON cookies.cookie_id = line_items.cookie_id \n",
      "WHERE users.username = :username_1\n"
     ]
    }
   ],
   "source": [
    "print(str(cookiemon_orders))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "统计所有用户各自的订单数量也常用，不只是当前的订单。可以通过`outerjoin()`方法实现，需要注意`join`的顺序，因为用`outerjoin()`方法生成的表会返回所有外键匹配结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('cakeeater', 1)\n",
      "('cookiemon', 1)\n",
      "('pieguy', 0)\n"
     ]
    }
   ],
   "source": [
    "columns = [users.c.username, func.count(orders.c.order_id)]\n",
    "all_orders = select(columns)\n",
    "all_orders = all_orders.select_from(users.outerjoin(orders))\n",
    "all_orders = all_orders.group_by(users.c.username) #后面介绍分组\n",
    "result = connection.execute(all_orders).fetchall()\n",
    "for row in result:\n",
    "    print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在，我们已经可以通过`join`实现关联查询了。但是，如果我们有一个像员工与老板关系表，用SQLAlchemy清楚的读取和理解内容需要用`alias`。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Aliases"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "用`join`的时候，通常要对一个表进行多次引用。在SQL里面，这是通过查询中的`aliases`实现的。例如，假设我们有下面的`schema`结构："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "employee_table = Table(\n",
    "    'employee', metadata,\n",
    "    Column('id', Integer, primary_key=True),\n",
    "    Column('manager_id', None, ForeignKey('employee.id')),\n",
    "    Column('name', String(255)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "现在假如我们想选择`Fred`手下的所有员工。在SQL里面，我们会这么做：\n",
    "```sql\n",
    "SELECT employee.name\n",
    "FROM employee, employee AS manager\n",
    "WHERE employee.manager_id = manager.id\n",
    "AND manager.name = 'Fred'\n",
    "```\n",
    "\n",
    "SQLAlchemy也允许用`alias()`方法实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "manager = employee_table.alias('mgr')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "stmt = select([employee_table.c.name],\n",
    "             and_(employee_table.c.id==manager.c.id,\n",
    "                 manager.c.name=='Fred'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT employee.name \n",
      "FROM employee, employee AS mgr \n",
      "WHERE employee.id = mgr.id AND mgr.name = :name_1\n"
     ]
    }
   ],
   "source": [
    "print(stmt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "SQLAlchemy也可以自动选择别名："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "manager = employee_table.alias()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "stmt = select([employee_table.c.name],\n",
    "             and_(employee_table.c.id==manager.c.id,\n",
    "                 manager.c.name=='Fred'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SELECT employee.name \n",
      "FROM employee, employee AS employee_1 \n",
      "WHERE employee.id = employee_1.id AND employee_1.name = :name_1\n"
     ]
    }
   ],
   "source": [
    "print(stmt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "数据分组`group_by`也是很有用的，下面我们来看看。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Grouping"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "SQLAlchemy可以对一个或多个列进行数据分组，然后统计各组的计数项（`count`），总和（`sum`）和其他统计参数，与SQL类似。下面我们看看每个客户的订单数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('cakeeater', 1)\n",
      "('cookiemon', 1)\n",
      "('pieguy', 0)\n"
     ]
    }
   ],
   "source": [
    "columns = [users.c.username, func.count(orders.c.order_id)]\n",
    "all_orders = select(columns)\n",
    "all_orders = all_orders.select_from(users.outerjoin(orders))\n",
    "all_orders = all_orders.group_by(users.c.username)\n",
    "result = connection.execute(all_orders).fetchall()\n",
    "for row in result:\n",
    "    print(row)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "前面的`join`的例子中我们已经用过，这里再看看`group_by`的用法。\n",
    "\n",
    "### Chaining"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "前面我们已经用过链式表达式，只是那时没有明说。进行数据查询时链式表达式能够清楚地显示查询的逻辑。因此，如果我们想用一个函数获取订单数据，可以如例3-28所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def get_orders_by_customer(cust_name):\n",
    "    columns = [orders.c.order_id, users.c.username, users.c.phone,\n",
    "                cookies.c.cookie_name, line_items.c.quantity, \n",
    "                line_items.c.extended_cost]\n",
    "    cust_orders = select(columns)\n",
    "    cust_orders = cust_orders.select_from(users.join(orders).join(line_items).join(cookies))\n",
    "    cust_orders = cust_orders.where(users.c.username == cust_name)\n",
    "    result = connection.execute(cust_orders).fetchall()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),\n",
       " (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "如果我们只想显示已发货或未发货的订单，怎么办？我们可以再写函数来支持其他选项，或者我们可以用链式查询来过滤。推荐后一种方法，尤其是处理复杂查询和制作报表时威力非常强大。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def get_orders_by_customer(cust_name, shipped=None, details=False):\n",
    "    columns = [orders.c.order_id, users.c.username, users.c.phone]\n",
    "    joins = users.join(orders)\n",
    "    if details:\n",
    "        columns.extend([cookies.c.cookie_name, line_items.c.quantity,\n",
    "                        line_items.c.extended_cost])\n",
    "        joins = joins.join(line_items).join(cookies)\n",
    "    cust_orders = select(columns)\n",
    "    cust_orders = cust_orders.select_from(joins)\n",
    "    cust_orders = cust_orders.where(users.c.username == cust_name)\n",
    "    if shipped is not None:\n",
    "        cust_orders = cust_orders.where(orders.c.shipped == shipped)\n",
    "    result = connection.execute(cust_orders).fetchall()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(2, 'cakeeater', '222-222-2222')]"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),\n",
       " (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater', details=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater', shipped=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(2, 'cakeeater', '222-222-2222')]"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater', shipped=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[(2, 'cakeeater', '222-222-2222', 'chocolate chip', 24, Decimal('12.00')),\n",
       " (2, 'cakeeater', '222-222-2222', 'oatmeal raisin', 6, Decimal('6.00'))]"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "get_orders_by_customer('cakeeater', shipped=False, details=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "到此为止，我们已经用SQL表达式语言的例子演示了SQLAlchemy Core。其实，你也可以直接用标准的SQL语言来进行。\n",
    "\n",
    "### Raw Queries\n",
    "\n",
    "在SQLAlchemy Core里面可以用原始的SQL语句进行操作，结果也是返回一个代理，后面的操作和SQLAlchemy Core的SQL表达式语法一样。除非必须，一般不推荐使用原始SQL，因为这么做存在安全隐患。下面我们简单演示一下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(1, 1, 0), (2, 2, 0)]\n"
     ]
    }
   ],
   "source": [
    "result = connection.execute('select * from orders').fetchall()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "有时候一些SQL小片段可以让语句表述更清晰。下面是用`text()`函数实现`where`的条件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[(1, None, 'cookiemon', 'mon@cookie.com', '111-111-1111', 'password', datetime.datetime(2015, 9, 1, 21, 37, 37, 531465), datetime.datetime(2015, 9, 1, 21, 37, 37, 531465))]\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy import text\n",
    "stmt = select([users]).where(text(\"username='cookiemon'\"))\n",
    "print(connection.execute(stmt).fetchall())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "通过本章介绍的增删改查等操作，现在你应该已经理解SQLAlchemy Core的SQL表达式用法了，用自己的数据库试试吧。下面我们来介绍SQLAlchemy的异常处理，以及事务处理`transactions`分组的用法。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "# Exceptions and Transactions\n",
    "\n",
    "前面做数据处理时，大部分工作我们都只用一行语句就搞定了，我们尽量避免做任何可能引起异常的事情，而本章我们会刻意搞点bug来演示异常处理方法。另外，我们还会介绍如何把对需要处理的任务分成单独的事务进行处理，保证每个事务都可以被适当地执行或正确地清理。\n",
    "\n",
    "## Exceptions\n",
    "\n",
    "SQLAlchemy会产生许多不同类型的异常；不过这里只重点介绍一些常见的异常：`AttributeErrors`和`IntegrityErrors`。通过对常用异常处理方法的学习，你可以掌握其他异常的处理方法。\n",
    "\n",
    "下面，请重新开一个Python shell或Notebook，然后用SQLAlchemy Core建立数据表。具体过程如例4-1所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String,\n",
    "                        DateTime, ForeignKey, Boolean, create_engine,\n",
    "                        CheckConstraint)\n",
    "metadata = MetaData()\n",
    "cookies = Table('cookies', metadata,\n",
    "                Column('cookie_id', Integer(), primary_key=True),\n",
    "                Column('cookie_name', String(50), index=True),\n",
    "                Column('cookie_recipe_url', String(255)),\n",
    "                Column('cookie_sku', String(55)),\n",
    "                Column('quantity', Integer()),\n",
    "                Column('unit_cost', Numeric(12, 2)),\n",
    "                CheckConstraint('quantity > 0', name='quantity_positive')\n",
    "                )\n",
    "users = Table('users', metadata,\n",
    "              Column('user_id', Integer(), primary_key=True),\n",
    "              Column('username', String(15), nullable=False, unique=True),\n",
    "              Column('email_address', String(255), nullable=False),\n",
    "              Column('phone', String(20), nullable=False),\n",
    "              Column('password', String(25), nullable=False),\n",
    "              Column('created_on', DateTime(), default=datetime.now),\n",
    "              Column('updated_on', DateTime(),\n",
    "                     default=datetime.now, onupdate=datetime.now)\n",
    "              )\n",
    "orders = Table('orders', metadata,\n",
    "               Column('order_id', Integer()),\n",
    "               Column('user_id', ForeignKey('users.user_id')),\n",
    "               Column('shipped', Boolean(), default=False)\n",
    "               )\n",
    "line_items = Table('line_items', metadata,\n",
    "                   Column('line_items_id', Integer(), primary_key=True),\n",
    "                   Column('order_id', ForeignKey('orders.order_id')),\n",
    "                   Column('cookie_id', ForeignKey('cookies.cookie_id')),\n",
    "                   Column('quantity', Integer()),\n",
    "                   Column('extended_cost', Numeric(12, 2))\n",
    "                   )\n",
    "engine = create_engine('sqlite:///:memory:')\n",
    "metadata.create_all(engine)\n",
    "connection = engine.connect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['users', 'cookies', 'line_items', 'orders'])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "metadata.tables.keys()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### AttributeError\n",
    "\n",
    "`AttributeError`是指获取一个不存在的属性时产生的异常。经常是在连接`ResultProxy`里没有的一列时发生。在尝试获取一个对象不存在的属性时`AttributeError`也会发生。在普通的Python代码里也会发生。这里单独拿出来说是因为SQLAlchemy里非常容易出现这类异常，而其产生的根源却很容易忽略。为了演示这类异常，我们在`users`表里插入一列数据，然后我们查询没有`selsect`的一列来诱发异常。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from sqlalchemy import select, insert\n",
    "ins = insert(users).values(\n",
    "    username=\"cookiemon\",\n",
    "    email_address=\"mon@cookie.com\",\n",
    "    phone=\"111-111-1111\",\n",
    "    password=\"password\"\n",
    ")\n",
    "result = connection.execute(ins)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cookiemon\n"
     ]
    },
    {
     "ename": "AttributeError",
     "evalue": "Could not locate column in row for column 'password'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[1;32md:\\programfiles\\Miniconda3\\lib\\site-packages\\sqlalchemy\\engine\\result.py\u001b[0m in \u001b[0;36m__getitem__\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m     69\u001b[0m             \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 70\u001b[1;33m                 \u001b[0mprocessor\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mobj\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mindex\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_keymap\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     71\u001b[0m             \u001b[1;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyError\u001b[0m: 'password'",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[1;31mNoSuchColumnError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32md:\\programfiles\\Miniconda3\\lib\\site-packages\\sqlalchemy\\engine\\result.py\u001b[0m in \u001b[0;36m__getattr__\u001b[1;34m(self, name)\u001b[0m\n\u001b[0;32m     95\u001b[0m             \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 96\u001b[1;33m                 \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     97\u001b[0m             \u001b[1;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32md:\\programfiles\\Miniconda3\\lib\\site-packages\\sqlalchemy\\engine\\result.py\u001b[0m in \u001b[0;36m__getitem__\u001b[1;34m(self, key)\u001b[0m\n\u001b[0;32m     71\u001b[0m             \u001b[1;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 72\u001b[1;33m                 \u001b[0mprocessor\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mobj\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mindex\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_parent\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_key_fallback\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     73\u001b[0m             \u001b[1;32mexcept\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32md:\\programfiles\\Miniconda3\\lib\\site-packages\\sqlalchemy\\engine\\result.py\u001b[0m in \u001b[0;36m_key_fallback\u001b[1;34m(self, key, raiseerr)\u001b[0m\n\u001b[0;32m    405\u001b[0m                     \u001b[1;34m\"Could not locate column in row for column '%s'\"\u001b[0m \u001b[1;33m%\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 406\u001b[1;33m                     expression._string_or_unprintable(key))\n\u001b[0m\u001b[0;32m    407\u001b[0m             \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mNoSuchColumnError\u001b[0m: \"Could not locate column in row for column 'password'\"",
      "\nDuring handling of the above exception, another exception occurred:\n",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-9-c4520631a10a>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mresult\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mresults\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0musername\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m     \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mresult\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpassword\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;32md:\\programfiles\\Miniconda3\\lib\\site-packages\\sqlalchemy\\engine\\result.py\u001b[0m in \u001b[0;36m__getattr__\u001b[1;34m(self, name)\u001b[0m\n\u001b[0;32m     96\u001b[0m                 \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     97\u001b[0m             \u001b[1;32mexcept\u001b[0m \u001b[0mKeyError\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 98\u001b[1;33m                 \u001b[1;32mraise\u001b[0m \u001b[0mAttributeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0me\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     99\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    100\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mAttributeError\u001b[0m: Could not locate column in row for column 'password'"
     ]
    }
   ],
   "source": [
    "s = select([users.c.username])\n",
    "results = connection.execute(s)\n",
    "for result in results:\n",
    "    print(result.username)\n",
    "    print(result.password)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "在例4-2中我们看到Python抛出了`AttributeError`并停止了程序，我们可以看到`AttributeError`是Python里常见的形式。首先显示错异常的类型，然后一个箭头会指明异常发生的位置，紧接着是异常发生源代码。最后一行会显示异常的具体内容，它会显示异常类型，以及为什么发生异常。这里出现异常的原因是ResultProxy里面没有`password`列，我们只查询了`username`列。这是在使用SQLAlchemy对象时出现的一个常见Python异常，还有一些SQLAlchemy自己特有的异常。下面就是其中一个：`IntegrityError`。\n",
    "\n",
    "### IntegrityError\n",
    "\n",
    "`IntegrityError`是另一个SQLAlchemy常见的异常，当我们做了不符合数据表或字段约束条件的事情时就会发生。当你请求的数据是唯一的，比如`users`表中的`username`,想创建两个同名用户时就会产生`IntegrityError`，演示程序如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "s = select([users.c.username])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('cookiemon',)]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "ins = insert(users).values(\n",
    "    username=\"cookiemon\",\n",
    "    email_address=\"damon@cookie.com\",\n",
    "    phone=\"111-111-1111\",\n",
    "    password=\"password\"\n",
    ")\n",
    "result = connection.execute(ins)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "和前面的`AttributeError`类似。首先显示错异常的类型，然后一个箭头会指明异常发生的位置，紧接着是异常发生源代码。最后一行会显示异常的具体内容，它会显示异常类型，以及为什么发生异常。这里指明了发生的原因：\n",
    "```\n",
    "UNIQUE constraint failed: users.username\n",
    "```\n",
    "这就告诉我们在`users`表的`username`里面插入同名用户是不允许的。之后的内容是SQLAlchemy表达式转变成的SQL语句，我们在第三章里介绍过，还有我们计划插入却产生异常的数据。程序在这里停止。\n",
    "\n",
    "当然会有很多种异常类型，这里介绍的两种是最常见的。SQLAlchemy里所有异常发生都会按照这两种方式产生。具体异常的内容请查看[SQLAlchemy文档](http://docs.sqlalchemy.org/en/latest/core/exceptions.html)。\n",
    "\n",
    "为了保证程序在发生异常时继续运行，我们需要实现异常处理方法。\n",
    "\n",
    "### Handling Errors\n",
    "\n",
    "要防止异常中断程序，我们需要正确地处理异常。这与Python的异常处理方法一样，用`try/except`代码块实现。例如，我们可以用`try/except`代码块捕捉异常显示信息，然后让后面的程序继续运行。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(sqlite3.IntegrityError) UNIQUE constraint failed: users.username [SQL: 'INSERT INTO users (username, email_address, phone, password, created_on, updated_on) VALUES (?, ?, ?, ?, ?, ?)'] [parameters: ('cookiemon', 'damon@cookie.com', '111-111-1111', 'password', '2015-09-01 13:45:18.991258', '2015-09-01 13:45:18.992259')]\n"
     ]
    }
   ],
   "source": [
    "from sqlalchemy.exc import IntegrityError\n",
    "\n",
    "ins = insert(users).values(\n",
    "    username=\"cookiemon\",\n",
    "    email_address=\"damon@cookie.com\",\n",
    "    phone=\"111-111-1111\",\n",
    "    password=\"password\"\n",
    ")\n",
    "try:\n",
    "    result = connection.execute(ins)\n",
    "except IntegrityError as error:\n",
    "    print(error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "虽然和前面例子代码一样，但是因为有`try/except`处理`IntegrityError`异常，所有结果就是简单的异常信息。这个例子只是演示了异常打印功能，其实我们可以在异常处理中写任何Python代码。返回异常信息告诉用户刚刚的操作失败了是很有用的做法。异常处理完成后，程序还会继续运行。虽然这里只处理了`IntegrityError`，但对其他SQLAlchemy异常也适用。\n",
    "\n",
    ">`try/except`里面的代码越少越好。因为代码太多可能会出现你意料之外的异常，不符合你捕捉的目标。\n",
    "\n",
    "用传统的Python方法可以捕捉一行语句的异常，如果我们有多个数据库语句，彼此之间互相关联，这个方法可能就不适用了。这时，我们需要将那些语句封装成一个数据库事务，SQLAlchemy提供了一个简单的包装来建立对象之间的链接：transactions。\n",
    "\n",
    "## Transactions\n",
    "\n",
    "我们不需要学习一堆数据库理论，可以把事务看成是一种确保多个数据库语句打包成一组运行成功或运行失败的处理方式。当启动一个事务的时候，我们记录数据库的状态，然后执行多条SQL语句。如果所有的SQL语句都能顺利执行，数据库就会不断的更新状态，忽略前面的状态，如下图所示。\n",
    "![](transactions1.png)\n",
    "但是，如果有一条语句运行失败了，整个数据库就要回退（rollback）到原来的状态，如下图所示。\n",
    "![](transactions2.png)\n",
    "举个我们可能会在之前建立的数据库里操作的例子。当客户买了我们的饼干之后，我们就需要把饼干邮寄给客户，同时更新库存量。但是，如果我们没有足够的饼干库存履行客户的订单需求，怎么办呢？我们就查检查库存，并且不邮寄订单。这就可以用事务解决。\n",
    "\n",
    "我们再新建一个Python Shell或Notebook，还用第三章的表，只是为`quantity`字段增加一个`CheckConstraint`限制条件，即库存量不能小于0。然后我们创建用户*cookiemon*，并设置*chocolate chip*和*dark chocolate chip cookie*的库存量，其中*chocolate chip*库存量为12，*dark chocolate chip cookie*库存量为1，具体程序如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from datetime import datetime\n",
    "from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String,\n",
    "                        DateTime, ForeignKey, Boolean, create_engine,\n",
    "                        CheckConstraint)\n",
    "\n",
    "metadata = MetaData()\n",
    "cookies = Table('cookies', metadata,\n",
    "                Column('cookie_id', Integer(), primary_key=True),\n",
    "                Column('cookie_name', String(50), index=True),\n",
    "                Column('cookie_recipe_url', String(255)),\n",
    "                Column('cookie_sku', String(55)),\n",
    "                Column('quantity', Integer()),\n",
    "                Column('unit_cost', Numeric(12, 2)),\n",
    "                CheckConstraint('quantity >= 0', name='quantity_positive')\n",
    "                )\n",
    "users = Table('users', metadata,\n",
    "              Column('user_id', Integer(), primary_key=True),\n",
    "              Column('username', String(15), nullable=False, unique=True),\n",
    "              Column('email_address', String(255), nullable=False),\n",
    "              Column('phone', String(20), nullable=False),\n",
    "              Column('password', String(25), nullable=False),\n",
    "              Column('created_on', DateTime(), default=datetime.now),\n",
    "              Column('updated_on', DateTime(),\n",
    "                     default=datetime.now, onupdate=datetime.now)\n",
    "              )\n",
    "orders = Table('orders', metadata,\n",
    "               Column('order_id', Integer()),\n",
    "               Column('user_id', ForeignKey('users.user_id')),\n",
    "               Column('shipped', Boolean(), default=False)\n",
    "               )\n",
    "line_items = Table('line_items', metadata,\n",
    "                   Column('line_items_id', Integer(), primary_key=True),\n",
    "                   Column('order_id', ForeignKey('orders.order_id')),\n",
    "                   Column('cookie_id', ForeignKey('cookies.cookie_id')),\n",
    "                   Column('quantity', Integer()),\n",
    "                   Column('extended_cost', Numeric(12, 2))\n",
    "                   )\n",
    "engine = create_engine('sqlite:///:memory:')\n",
    "metadata.create_all(engine)\n",
    "connection = engine.connect()\n",
    "\n",
    "from sqlalchemy import select, insert, update\n",
    "ins = insert(users).values(\n",
    "    username=\"cookiemon\",\n",
    "    email_address=\"mon@cookie.com\",\n",
    "    phone=\"111-111-1111\",\n",
    "    password=\"password\"\n",
    ")\n",
    "result = connection.execute(ins)\n",
    "ins = cookies.insert()\n",
    "inventory_list = [\n",
    "    {\n",
    "        'cookie_name': 'chocolate chip',\n",
    "        'cookie_recipe_url': 'http://some.aweso.me/cookie/recipe.html',\n",
    "        'cookie_sku': 'CC01',\n",
    "        'quantity': '12',\n",
    "        'unit_cost': '0.50'\n",
    "    },\n",
    "    {\n",
    "        'cookie_name': 'dark chocolate chip',\n",
    "        'cookie_recipe_url': 'http://some.aweso.me/cookie/recipe_dark.html',\n",
    "        'cookie_sku': 'CC02',\n",
    "        'quantity': '1',\n",
    "        'unit_cost': '0.75'\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, inventory_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('chocolate chip', 12), ('dark chocolate chip', 1)]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "现在，我们再定义两个*cookiemon*的订单，第一条订单是9块*chocolate chip*，第二条订单是4块*chocolate chip*和1块*dark chocolate chip cookie*。我们用插入语句来实现，具体如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ins = insert(orders).values(user_id=1, order_id='1')\n",
    "result = connection.execute(ins)\n",
    "ins = insert(line_items)\n",
    "order_items = [\n",
    "    {\n",
    "        'order_id': 1,\n",
    "        'cookie_id': 1,\n",
    "        'quantity': 9,\n",
    "        'extended_cost': 4.50\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, order_items)\n",
    "ins = insert(orders).values(user_id=1, order_id='2')\n",
    "result = connection.execute(ins)\n",
    "ins = insert(line_items)\n",
    "order_items = [\n",
    "    {\n",
    "        'order_id': 2,\n",
    "        'cookie_id': 2,\n",
    "        'quantity': 1,\n",
    "        'extended_cost': 0.75\n",
    "    },\n",
    "    {\n",
    "        'order_id': 2,\n",
    "        'cookie_id': 1,\n",
    "        'quantity': 4,\n",
    "        'extended_cost': 2.00\n",
    "    }\n",
    "]\n",
    "result = connection.execute(ins, order_items)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "这样我们就有了演示事务的订单数据了，现在我们需要定义一个函数`ship_it`。这个函数接受一个`order_id`，然后从库存中去掉对应的购买量，并把订单标记成已发货，`shipped=True`，如下所示。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sqlalchemy.exc import IntegrityError\n",
    "def ship_it(order_id):\n",
    "    try:\n",
    "        s = select([line_items.c.cookie_id, line_items.c.quantity])\n",
    "        s = s.where(line_items.c.order_id == order_id)\n",
    "        cookies_to_ship = connection.execute(s)\n",
    "        for cookie in cookies_to_ship:\n",
    "            u = update(cookies).where(cookies.c.cookie_id == cookie.cookie_id)\n",
    "            u = u.values(quantity=cookies.c.quantity - cookie.quantity)\n",
    "            result = connection.execute(u)\n",
    "        u = update(orders).where(orders.c.order_id == order_id)\n",
    "        u = u.values(shipped=True)\n",
    "        result = connection.execute(u)\n",
    "        print(\"Shipped order ID: {}\".format(order_id))\n",
    "    except IntegrityError as error:\n",
    "        print(error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "当一条订单发货之后，函数`ship_it`就会执行动作。让我们对第一条订单执行函数`ship_it`，然后看看`cookies`表是否更新了库存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Shipped order ID: 1\n"
     ]
    }
   ],
   "source": [
    "ship_it(1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('chocolate chip', 3), ('dark chocolate chip', 1)]"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "运行正常。但是现在的库存量不能满足第二条订单；但是，在工作节奏很快的仓库中，这些订单应该可以同时处理。现在我们再用函数`ship_it`处理一下第二条订单。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(sqlite3.IntegrityError) CHECK constraint failed: quantity_positive [SQL: 'UPDATE cookies SET quantity=(cookies.quantity - ?) WHERE cookies.cookie_id = ?'] [parameters: (4, 1)]\n"
     ]
    }
   ],
   "source": [
    "ship_it(2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('chocolate chip', 3), ('dark chocolate chip', 0)]"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "程序中库存量先扣减1块*dark chocolate chip cookie*，可以正常执行，再扣减4块*chocolate chip*，因为没有足够的`chocolate chip`库存导致了`IntegrityError`异常。但是`dark chocolate chip`的库存扣减了，这不是我们想看到的。我们这里想要发生整个订单，不允许单独让一部分先发货。用前面介绍的异常处理方法可以解决这个问题，但是，事务提供了更好的处理方式。\n",
    "\n",
    "事务通过`connection`对象的`begin()`方法启动。这样我们就获得一个事务，可以处理后面所有的语句。如果这些语句都成功执行，我们就可以用`commit()`方法对数据库进行状态确认。如果不完全成功，我们就用`rollback()`方法让数据库回退到原始状态。下面让我们用事务把函数`ship_it`改一下。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def ship_it(order_id):\n",
    "    s = select([line_items.c.cookie_id, line_items.c.quantity])\n",
    "    s = s.where(line_items.c.order_id == order_id)\n",
    "    transaction = connection.begin()\n",
    "    cookies_to_ship = connection.execute(s).fetchall()\n",
    "    try:\n",
    "        for cookie in cookies_to_ship:\n",
    "            u = update(cookies).where(cookies.c.cookie_id == cookie.cookie_id)\n",
    "            u = u.values(quantity=cookies.c.quantity-cookie.quantity)\n",
    "            result = connection.execute(u)\n",
    "        u = update(orders).where(orders.c.order_id == order_id)\n",
    "        u = u.values(shipped=True)\n",
    "        result = connection.execute(u)\n",
    "        print(\"Shipped order ID: {}\".format(order_id))\n",
    "        transaction.commit()\n",
    "    except IntegrityError as error:\n",
    "        transaction.rollback()\n",
    "        print(error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们把`dark chocolate chip`的库存重新补成1。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "u = update(cookies).where(cookies.c.cookie_name == \"dark chocolate chip\")\n",
    "u = u.values(quantity = 1)\n",
    "result = connection.execute(u)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('chocolate chip', 3), ('dark chocolate chip', 1)]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用新的函数`ship_it`对第二条订单进行处理。程序不会因为异常而停止，只会打印异常信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(sqlite3.IntegrityError) CHECK constraint failed: quantity_positive [SQL: 'UPDATE cookies SET quantity=(cookies.quantity - ?) WHERE cookies.cookie_id = ?'] [parameters: (4, 1)]\n"
     ]
    }
   ],
   "source": [
    "ship_it(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "再用库存查看语句看看库存的状态，回退到第二条订单处理之前的状态了。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('chocolate chip', 3), ('dark chocolate chip', 1)]"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = select([cookies.c.cookie_name, cookies.c.quantity])\n",
    "connection.execute(s).fetchall()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "这就是事务的作用，短短几行代码就可以让数据库回退到异常发生之前的状态，非常给力吧。\n",
    "\n",
    "本章我们介绍了单行语句和成组的多行语句的异常处理方法。对单行语句可以通过`try/except`来防止程序因为出现异常而中断。我们还介绍了事务的处理方法，保证应用在处理成组的多行语句时不发生中断。现在，我们还需要学习如何测试代码的方法，保证其行为符合我们的预期，让我们开始下一章吧。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
